const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()

const views = require('koa-views')
const co = require('co')
const convert = require('koa-convert')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const debug = require('debug')('koa2:server')
const path = require('path')
const cors = require('koa2-cors');//引入跨域

const config = require('./config')
const routes = require('./routes')
const { title } = require('process')

const port = process.env.PORT || config.port

// error handler
onerror(app)

// middlewares
app.use(bodyparser())
  .use(json())
  .use(logger())
  .use(cors({//允许跨域
    credentials: true
  })) 
  .use(require('koa-static')(__dirname + '/public'))
  .use(views(path.join(__dirname, '/views'), {
    options: {settings: {views: path.join(__dirname, 'views')}},
    map: {'njk': 'nunjucks'},
    extension: 'njk'
  }))
  .use(router.routes())
  .use(router.allowedMethods())

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - $ms`)
})

// router.get('/', async (ctx, next) => {
//   // ctx.body = 'Hello World'
//   ctx.state = {
//     title: 'Koa2'
//   }
//   await ctx.render('index', ctx.state)
// })

router.get('/', async (ctx, next) => {
  //默认是get请求
  //get接受参数方式ctx.request.query  ctx可以获取当前函数的上下文，相当于this的请求
  const query = ctx.request.query
  if(query.user == 'di'){
    ctx.response.body = {
      user:{
        name:'didi',
        age:19,
      }
    }
  }else{
    ctx.response.body = {
      user:{
        name:'222',
        age:22,
      }
    }
  }
})
//不同类型之间路径可以是重复的
router.post('/',async (ctx,next) => {
  const query = ctx.request.body;//用户给我们传的参数用ctx.request.body接收
  console.log('query',query)
  ctx.response.body = {//返回给用户的数据
    type:'post',
    success:query
  }
})

const personal = [
  {name:'did',pass:'123456',school:'家里蹲',gender:'男'},
  {name:'dada',pass:'232323',school:'am',gender:'女'},
]
function getREsp(bool, msg) {
  return {
    success:bool,
    message:msg
  }
}

router.post('/regist',async (ctx,next) => {
  // const query = ctx.request.body;//用户给我们传的参数用ctx.request.body接收
  const {username, password} = ctx.request.body;
  console.log(ctx.request.body)
  //判断用户名是否重复
  var list = personal.find( item =>  item.name == username )
  //如果重复进行的操作
  if(list){
    console.log('========>1');
    ctx.response.body = getREsp(false,'用户名重复')
  }else{
    //判断密码是否符合规则
    let reg = /^[0-9 a-z A-Z]{6,16}$/
    let reg2 = /^[0-9 a-z A-Z]{4,12}$/
    if(!reg2.test(username) ){
      console.log('=========>2');
      ctx.response.body =  getREsp(false,'用户名长度不符合,请输入4-12位数字字母组成的密码')
    }else if(!reg.test(password)){
      ctx.response.body =  getREsp(false,'密码长度不符合,请输入6-16位数字字母组成的密码')
    }else{
      console.log('========>3');
      //注册
      personal.push({
        name:username,
        pass:password
      });
      ctx.response.body = getREsp(true, '注册成功')
    }
  }
})
router.post('/user/login',async (ctx,next) => {
  const {username, password} = ctx.request.body
  const user = personal.find(item => item.name == username)
  if( !user ){
    //用户名不存在
    ctx.response.body = getREsp(false,'没有找到该用户名，请先注册!!')
  }else{
    if(user.pass !== password){
      //密码错误，用户名存在
      ctx.response.body = getREsp(false,'密码输入错误')
    }else{
      let result = getREsp(true,'成功')
      result['data'] = ctx.response.body
      ctx.response.body = result;
    }
  }
})

const list = [
  {active:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201905%2F28%2F20190528143150_fETNW.thumb.700_0.jpeg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625119378&t=4a6c262c8905968cd9cbf8c50cd0d1c6',
  title:'111'
},
  {active:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic2.zhimg.com%2F50%2Fv2-5bcf79fce14ac8c7ed2e1584bb7015b0_hd.jpg&refer=http%3A%2F%2Fpic2.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625119378&t=544399f40168d9598fa50f9a68f084a2',
  title:'222'
},
  {active:'https://pic1.zhimg.com/v2-6dd95e7aa86a5ea8ffb0d00c78e1cb8c_xs.jpg?source=1940ef5c',
  title:'333'
},
  {active:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201809%2F01%2F20180901190625_wmpeq.thumb.700_0.jpeg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625119378&t=93c00f75f905a54bbb572f8113fbfffa',
  title:'444'
},
  {active:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic3.zhimg.com%2F50%2Fv2-44df45023c1df566a0e2b7addce3b95e_hd.jpg&refer=http%3A%2F%2Fpic3.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625119378&t=7960c01ab69421e9ec4d484f6110da4b',
  title:'555'
},
  {active:'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3155998395,3600507640&fm=26&gp=0.jpg',
  title:'666'
},
  {active:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic2.zhimg.com%2F50%2Fv2-f1e642375f2b575dfb6a8c8e69338d3c_hd.jpg&refer=http%3A%2F%2Fpic2.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625119378&t=57c95348e778be6039eb267fe0347bf8',
  title:'77'
},
  {active:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F202003%2F31%2F20200331204349_E8RtP.thumb.1000_0.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625119378&t=8f135b78feb30cfe1a810c1bda2348b6',
  title:'888'
},
  {active:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic4.zhimg.com%2F50%2Fv2-5a63ee9cbe62d53ee36e1c99caa095d9_hd.jpg&refer=http%3A%2F%2Fpic4.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625119378&t=5716c16c0ede44969f8466e8070096f6',
title:'999'
},
  {active:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201705%2F03%2F20170503153413_xGSNu.thumb.700_0.jpeg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625119378&t=35e7cf48a4ed6544b695300d131ee5f8',
  title:'1010'
},
  {active:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic2.zhimg.com%2F50%2Fv2-6dafbcb68aa87c7e1d71b290005de819_hd.jpg&refer=http%3A%2F%2Fpic2.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625119561&t=b01700f64fecbadfe14f3a54a1f8fc25',
  title:'11 11'
},
  {active:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fcdn.duitang.com%2Fuploads%2Fitem%2F201310%2F24%2F20131024105254_xRZCX.thumb.600_0.gif&refer=http%3A%2F%2Fcdn.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625119561&t=5e7085dc02f8294f6f4b56be01a68376',
  title:'1212'
},
  {active:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fdp.gtimg.cn%2Fdiscuzpic%2F0%2Fdiscuz_x5_gamebbs_qq_com_forum_201306_19_1256219xc797y90heepdbh.jpg%2F0&refer=http%3A%2F%2Fdp.gtimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625119561&t=254c5bbf5d70b7395199b68836a50a22',
  title:'1313'
},
]

router.post('/show', async (ctx, next) => {
  const { page, size } = ctx.request.body;
  let arr = list.slice( (page - 1) * size,page * size)
  ctx.response.body = {//返回给用户的数据
    type:'post',
    success:true,
    data:arr
  }
})

routes(router)
app.on('error', function(err, ctx) {
  console.log(err)
  logger.error('server error', err, ctx)
})

module.exports = app.listen(config.port, () => {
  console.log(`Listening on http://localhost:${config.port}`)
})
